import { formatAmisLayout, getCurrentWindow, getUIUpdater, udp, updateAmisLayout, OType } from '@cscec/udp-ui';
import React, { useContext } from 'react';
import { QueryParamName } from './constVar';

export interface ICtx<P = any> {
  page: P;
  capacity?: object,
  microServiceName: string;
  nextRoute: string;
  refreshKey: object;
  uiInfo: any;
  forceUpdate: () => void;
  updateUI: (updater: Function) => void;
}

export const PageContext = React.createContext<Partial<ICtx>>({ nextRoute: '' });

export function usePageCtx<P = any>() {
  return useContext(PageContext) as ICtx<P>;
}

export function initPage(busType?: string) {
  return { busType: udp.getQueryValue(QueryParamName.busType) || busType };
}

export function initProviderValue<P = any>(page: P, nextRoute: string): ICtx<P> {
  const p = page as any;
  const { listInfo, editInfo, capacity, microServiceName, billNoRule, tableColPermission, attachmentProperty } = p.props;
  let uiInfo = p.isList ? listInfo : editInfo;
  const { layout } = formatAmisLayout(uiInfo);
  getCurrentWindow()['ui_layout_config'] = { layoutConfig: uiInfo, layout, busType: p.busType, extendProperty: { billNoRule, attachmentProperty } };
  if (!p.isList) {
    // 编码规则字段权限控制
    if (billNoRule?.length) {
      const newUI = getUIUpdater(layout)((updater) => {
        const fieldProps = {};
        billNoRule.forEach((u) => {
          fieldProps[`${u.tableName}.${u.noField}`] = { disabled: true };
        });
        updater.setFieldProps(fieldProps);
      });
      getCurrentWindow('ui_layout_config').layout = newUI.layout;
      uiInfo = updateAmisLayout(uiInfo, newUI.layout);
    }
  }
  const oType = udp.getQueryValue('oType');
  // 表列字段权限控制+新增时不控制
  if (tableColPermission?.length && oType !== OType.Add) {
    const newUI = getUIUpdater(layout)((updater) => {
      const fieldProps = {};
      tableColPermission.forEach((u) => {
        u.fieldList?.forEach((f) => {
          const rightKey = +f.rightKey;
          if (rightKey === 1) {
            fieldProps[`${u.tableName}.${f.fieldName}`] = { disabled: true };
          } else if (rightKey === 0) {
            fieldProps[`${u.tableName}.${f.fieldName}`] = { disabled: true, encrypted: true };
          }
        });
      });
      updater.setFieldProps(fieldProps);
    });
    getCurrentWindow('ui_layout_config').layout = newUI.layout;
    uiInfo = updateAmisLayout(uiInfo, newUI.layout);
  }

  return {
    page,
    capacity,
    microServiceName,
    nextRoute,
    uiInfo,
    refreshKey: {},
    forceUpdate() {
      p.setState((prev: any) => ({
        ...prev,
        providerValue: {
          ...prev.providerValue,
          refreshKey: {}
        }
      }));
    },
    updateUI(updater) {
      p.setState((prev: any) => ({
        ...prev,
        providerValue: {
          ...prev.providerValue,
          uiInfo: updater(prev.uiInfo),
        }
      }));
    },
  };
}
